/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    	if (head == NULL) {
			return head;
		}
		ListNode* pre = head;
		ListNode* post = head;
		for (int i = 0; i < n; ++i) {
			post = post->next;
		}
		if (post == NULL) { // delete the head
			head = head->next;
			return head;
		}

		while (post->next) {
			pre = pre->next;
			post = post->next;
		}
		pre->next = pre->next->next;
		return head;
    }
};